#!/usr/bin/python3

from PyQt6.QtWidgets import QMainWindow, QFileDialog, QMessageBox

from widgets.ui.RepeatExcelLine import Ui_MainWindow
from excel.RepeatLine import repeat_line


# 自定义窗口类
# 参数1: QMainWindow 用来装载你需要的各种组件、控件
# 参数2: Ui_MainWindow 通过Qt设计师生成的py的窗口类
class RepeatExcelLineController(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        """
        子类的初始化方法，继承QMainWindow父类
        :param parent:
        """
        QMainWindow.__init__(self, parent=parent)  # 初始化QMainWindow方法
        self.setupUi(self)  # 调用Ui_MainWindow类的setupUi方法，从中获取Ui界面

        # 按钮点击绑定事件，并调用btnClicked方法

        self.select_source_file_btn.clicked.connect(lambda: self.selectFile(self.select_source_file_line))
        self.select_target_file_btn.clicked.connect(lambda: self.selectFile(self.select_target_file_line))
        self.confirmBtn.clicked.connect(self.btnClicked)

    def selectFile(self, file_line):
        fd = QFileDialog()
        fd.setFileMode(QFileDialog.FileMode.ExistingFile)  # 设置多选
        # fd.setDirectory('C:\\')  # 设置初始化路径
        fd.setNameFilter('Excel文件(*.xlsx *.xls)')
        if fd.exec():  # 执行
            # print(fd.selectedFiles()[0])
            file_line.setText(fd.selectedFiles()[0])

    def btnClicked(self):
        try:
            source_file = self.select_source_file_line.text()
            target_file = self.select_target_file_line.text()
            head_row = self.head_line_number_box.value()
            repeat_row = self.repeat_line_number_box.value()

            if source_file == '' or target_file == '':
                QMessageBox.information(self, '提示', '文件不能为空')
                return

            QMessageBox.information(self, "消息", f'source_file:{source_file}\n'
                                                f'target_file:{target_file}\n'
                                                f'head_row:{head_row}\n'
                                                f'repeat_row:{repeat_row}\n')
            repeat_line(source_file, target_file, head_row=head_row, repeat_row=repeat_row)
        except Exception as e:
            QMessageBox.information(self, '异常', str(e))
        else:
            QMessageBox.information(self, '提示', '执行成功')
